<template>
  <div>
    <a-steps :current="current" :items="items" type="navigation" @change="stepsChange" />
    <div class="steps-content">
      <!-- {{ steps[current].content }} -->
      <a-form ref="formRef" :model="applicationForm" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <div v-show="current == 0">
          <a-form-item ref="name" label="报名序号" name="registerNum">
            <a-input v-model:value="applicationForm.registerNum" :disabled="true" />
          </a-form-item>
          <!-- <a-form-item label="报名类别"
                       name="hireType">
            <a-select v-model:value="applicationForm.hireType"
                      placeholder="请选择报名类别"
                      :options="hireTypeList">
            </a-select>
          </a-form-item> -->
          <a-form-item label="报名学校类别" name="registerType">
            <a-select
              v-model:value="applicationForm.registerType"
              @change="schooleTypeChange"
              placeholder="请选择报名学校类别"
              :options="registerTypeList"
              :disabled="applicationForm.isPass == 1"
            />
          </a-form-item>
          <a-form-item label="报名任教学校" name="registerSchool">
            <a-select
              v-model:value="applicationForm.registerSchool"
              @change="registerSchoolChange"
              placeholder="请选择报名任教学校"
              :options="registerSchoolList"
              :disabled="applicationForm.isPass == 1"
            >
              <!--              <a-select-option v-for="(i, k) in registerSchoolList" :value="i.registerSchool">{{ i.ORGNAME }}</a-select-option>-->
            </a-select>
          </a-form-item>
          <a-form-item label="岗位代码类别" name="jobCode">
            <a-select
              v-model:value="applicationForm.jobCode"
              placeholder="请选择岗位代码"
              :options="jobCodeList"
              :disabled="applicationForm.isPass == 1"
            />
          </a-form-item>
          <a-form-item label="报名学科" name="subject">
            <a-select v-model:value="applicationForm.subject" placeholder="请选择报名学科" :disabled="applicationForm.isPass == 1">
              <a-select-option v-for="(item, index) in subjectList22" :key="index" :value="item.subject">{{ item.subject }}</a-select-option>
            </a-select>
          </a-form-item>
        </div>

        <div v-show="current == 1">
          <a-row justify="space-evenly">
            <a-col :span="12">
              <a-form-item ref="name" label="照片" name="picUrl">
                <a-upload
                  v-model:file-list="fileList"
                  action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                  list-type="picture-card"
                  :customRequest="customRequest"
                  @change="handleChange"
                  @preview="handlePreview"
                  maxCount="1"
                >
                  <div v-if="fileList.length < 8">
                    <plus-outlined />
                    <div style="margin-top: 8px">上传</div>
                  </div>
                </a-upload>
                <span style="font-size: 12px; color: red">照片请上传一寸证件照</span>
              </a-form-item>
              <!-- <a-modal v-if="detailType"  :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
                <img  alt="example" style="width: 100%" :src="baseUrl + '/upload/' + applicationForm.picUrl" />
              </a-modal> -->

              <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>
            </a-col>
          </a-row>
          <!--          <a-row justify="space-evenly">
            <a-col :span="12">
              &lt;!&ndash; <a-form-item ref="name" label="图片" name="fileList">
                <a-upload
                  v-model:file-list="fileList"
                  action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                  list-type="picture-card"
                  @preview="handlePreview"
                  maxCount="1"
                  accept="image/png,image/jpeg"
                >
                  <div v-if="fileList.length < 8">
                    <plus-outlined />
                    <div style="margin-top: 8px">上传</div>
                  </div>
                </a-upload>
                <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
                  <img alt="example" style="width: 100%" :src="previewImage" />
                </a-modal>
              </a-form-item> &ndash;&gt;
              <a-form-item label="图片" name="fileList">
                <br />
&lt;!&ndash;                <a-upload
                  name="fileList"
                  list-type="picture-card"
                  class="avatar-uploader"
                  :show-upload-list="false"
                  :headers="{ 'x-access-token': useUserStore().getToken }"
                  :customRequest="customRequest"
                  @preview="handlePreview"
                  maxCount="1"
                >&ndash;&gt;
                <a-upload
                    v-model:file-list="fileList"
                    list-type="picture-card"
                    :customRequest="customRequest"
                    @preview="handlePreview"
                    maxCount="1"
                >
&lt;!&ndash;                  <div class="avatar-container">
                    <img :src="picUrl" class="avatar-image" alt="avatar" />
                    <div class="overlay">
                      <span>上传</span>
                    </div>
                  </div>&ndash;&gt;
                  <div v-if="fileList.length < 8">
                    <plus-outlined />
                    <div style="margin-top: 8px">上传</div>
                  </div>
                  &lt;!&ndash; <div v-else>
                    <loading-outlined v-if="updateAvatarLoading" />
                    <plus-outlined v-else />
                    <div class="ant-upload-text">上传2</div>
                  </div> &ndash;&gt;
                </a-upload>
              </a-form-item>
            </a-col>
          </a-row>-->
          <a-row justify="space-evenly">
            <a-col :span="12">
              <a-form-item ref="name" label="姓名" name="actualName">
                <a-input v-model:value="applicationForm.actualName" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="性别" name="gender">
                <a-radio-group v-model:value="applicationForm.gender" disabled>
                  <a-radio :value="1">男</a-radio>
                  <a-radio :value="2">女</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="12" v-for="(item, index) in formList" :key="index">
              <a-form-item :label="item.label" :name="item.name">
                <a-input v-if="item.type === 'input'" v-model:value="applicationForm[item.name]" />
                <a-input v-if="item.type === 'inputNumber'" v-model:value="applicationForm[item.name]" suffix="CM" />
                <!-- <a-input-number style="width: 100%;" v-if="item.type === 'inputNumber'"
                  v-model:value="applicationForm[item.name]" suffix="CM" /> -->
                <a-radio-group v-if="item.type === 'radio'" v-model:value="applicationForm[item.name]">
                  <a-radio v-for="i in item.options" :key="i" :value="i.value">{{ i.label }}</a-radio>
                </a-radio-group>
                <a-date-picker
                  style="width: 100%"
                  v-if="item.type === 'datePicker'"
                  v-model:value="applicationForm[item.name]"
                  valueFormat="YYYY-MM-DD"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item ref="name" label="身份证号" name="card">
                <a-input v-model:value="applicationForm.card" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item ref="name" label="出生年月" name="birthday">
                <!-- <a-input v-model:value="applicationForm.birthday" /> -->
                <a-date-picker v-model:value="applicationForm.birthday"   style="width: 100%" :valueFormat="'YYYY-MM-DD'"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item ref="name" label="通讯地址" name="mailAddress">
                <a-input v-model:value="applicationForm.mailAddress" maxlength="300" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item ref="name" label="邮政编码" name="postalCode">
                <a-input v-model:value="applicationForm.postalCode" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item ref="name" label="手机号码" name="phone">
                <a-input v-model:value="applicationForm.phone" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item ref="name" label="电子邮箱" name="email">
                <a-input v-model:value="applicationForm.email" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item ref="name" label="户籍所在地" name="houseLocation">
                <a-input v-model:value="applicationForm.houseLocation" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item ref="name" label="民族" name="ethnicGroupId">
                <a-select v-model:value="applicationForm.ethnicGroupId" placeholder="请选择政治面貌">
                  <a-select-option v-for="(i, k) in ethnicGroupList" :key="k" :value="i.ethnicGroupId">{{ i.ethnicGroupName }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item ref="name" label="政治面貌" name="political">
                <a-select v-model:value="applicationForm.political" placeholder="请选择政治面貌">
                  <a-select-option v-for="(i, k) in politicalList" :key="k" :value="i.content">{{ i.title }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item ref="name" label="婚姻状况" name="marital">
                <a-select v-model:value="applicationForm.marital" placeholder="请选择婚姻状况">
                  <a-select-option v-for="(i, k) in maritalList" :key="k" :value="i.content">{{ i.title }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <div v-show="current == 2">
          <div style="padding: 20px">
            <a-card title="本人简历(高中起)" style="width: 100%">
              <a-table :dataSource="dataSource1" :columns="columns1" bordered>
                <template #bodyCell="{ record, column }">
                  <template v-if="column.dataIndex == 'enrollmentDate'">
                    <a-date-picker v-model:value="record.enrollmentDate" valueFormat="YYYY-MM-DD" />
                  </template>
                  <template v-if="column.dataIndex == 'graduationDate'">
                    <a-date-picker v-model:value="record.graduationDate" valueFormat="YYYY-MM-DD" />
                  </template>
                  <template v-if="column.dataIndex == 'school'">
                    <a-input v-model:value="record.school" />
                  </template>
                  <template v-if="column.dataIndex == 'post'">
                    <a-input v-model:value="record.post" />
                  </template>
                </template>
                <template #operation="{ record }">
                  <a-popconfirm v-if="dataSource1.length" title="确认删除?" @confirm="onDelete1(record)">
                    <a>删除</a>
                  </a-popconfirm>
                </template>
              </a-table>
              <a-button class="editable-add-btn" @click="handleAdd1" style="margin-bottom: 8px; margin-top: 20px">添加</a-button>
            </a-card>
          </div>
        </div>
        <div v-show="current == 3">
          <div style="padding: 20px">
            <a-card title="个人所得证书及获奖情况" style="width: 100%">
              <a-table :dataSource="dataSource2" :columns="columns2" bordered>
                <template #bodyCell="{ record, column }">
                  <template v-if="column.dataIndex == 'issuanceDate'">
                    <a-date-picker v-model:value="record.issuanceDate" valueFormat="YYYY-MM-DD" />
                  </template>
                  <template v-if="column.dataIndex == 'issuanceDepartment'">
                    <a-input v-model:value="record.issuanceDepartment" />
                  </template>
                  <template v-if="column.dataIndex == 'awardName'">
                    <a-input v-model:value="record.awardName" />
                  </template>
                  <template v-if="column.dataIndex == 'grade'">
                    <a-input v-model:value="record.grade" />
                  </template>
                </template>
                <template #operation="{ record }">
                  <a-popconfirm v-if="dataSource2.length" title="确认删除?" @confirm="onDelete2(record.sort)">
                    <a>删除</a>
                  </a-popconfirm>
                </template>
              </a-table>
              <a-button class="editable-add-btn" @click="handleAdd2" style="margin-bottom: 8px; margin-top: 20px">添加</a-button>
            </a-card>
          </div>
        </div>

        <div v-show="current == 4">
          <a-form-item label="英语等级" name="english">
            <a-select v-model:value="applicationForm.english" placeholder="请选择英语等级">
              <a-select-option v-for="(i, k) in englishList" :key="k" :value="i.content">{{ i.title }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="普通话等级" name="mandarin">
            <a-select v-model:value="applicationForm.mandarin" placeholder="请选择普通话等级">
              <a-select-option v-for="(i, k) in mandarinList" :key="k" :value="i.content">{{ i.title }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="普通话发证地" name="mandarinPlace">
            <a-input v-model:value="applicationForm.mandarinPlace" />
          </a-form-item>
          <a-form-item label="计算机等级" name="computerLevel">
            <a-select v-model:value="applicationForm.computerLevel" placeholder="请选择计算机等级">
              <a-select-option v-for="(i, k) in ['无', '一级', '二级', '三级', '四级']" :key="k" :value="i">{{ i }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="教师资格证类别" name="teacherCardType">
            <a-select v-model:value="applicationForm.teacherCardType" placeholder="请选择教师资格证类别" @change="teacherCardTypeChange">
              <a-select-option v-for="(i, k) in teacherCardTypeList" :key="k" :value="i.content">{{ i.title }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="教师资格证学科" name="teacherCardSubject">
            <a-select v-model:value="applicationForm.teacherCardSubject" placeholder="请选择教师资格证学科">
              <a-select-option v-for="(i, k) in SubjectList" :key="k" :value="i">{{ i }}</a-select-option>
            </a-select>
          </a-form-item>
        </div>
        <div v-show="current == 5">
          <a-form-item label="就读院校" name="almaMater">
            <a-input v-model:value="applicationForm.almaMater" />
          </a-form-item>
          <!-- <a-form-item label="入校时间" name="enrollmentData">
            <a-input v-model:value="applicationForm.enrollmentData" />
          </a-form-item>
          <a-form-item label="毕业时间" name="graduationData">
            <a-input v-model:value="applicationForm.graduationData" />
          </a-form-item> -->
          <a-form-item label="入校时间" name="enrollmentData">
            <a-date-picker style="width: 100%" v-model:value="applicationForm.enrollmentData" valueFormat="YYYY-MM-DD" />
            <!-- <a-date-picker v-model:value="applicationForm.enrollmentData" show-time type="date" placeholder="请选择入校时间"
              style="width: 100%" /> -->
          </a-form-item>
          <a-form-item label="毕业时间" name="graduationData">
            <a-date-picker style="width: 100%" v-model:value="applicationForm.graduationData" valueFormat="YYYY-MM-DD" />
            <!-- <a-date-picker v-model:value="applicationForm.graduationData" show-time type="date" placeholder="请选择毕业时间"
              style="width: 100%" /> -->
          </a-form-item>
          <a-form-item label="主修专业" name="major">
            <a-textarea v-model:value="applicationForm.major" />
          </a-form-item>
          <a-form-item label="学历" name="education">
            <a-select v-model:value="applicationForm.education" placeholder="请选择学历">
              <a-select-option v-for="(i, k) in educationList" :key="k" :value="i.content">{{ i.title }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="学位" name="academicDegree">
            <a-select v-model:value="applicationForm.academicDegree" placeholder="请选择学位">
              <a-select-option v-for="(i, k) in academicDegreeList" :key="k" :value="i.content">{{ i.title }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="附件" name="fileUrl">
            <p style="font-size: 12px; text-align: left">
              提交材料：<br />
              （1）《2025年崇明区教育系统教师招聘报名信息表》；<br />
              （2）身份证和户口簿；<br />
              （3）学历学位证书（应届生提供学生证和就业推荐表）；<br />
              （4）教师资格证或中小学教师资格考试合格证明；<br />
              （5）普通话和英语等级证书；<br />
              （6）报考岗位要求的其他证件材料。
            </p>
            <p style="color: red">请将上述文件打包为一个压缩包(.zip)后上传</p>
            <a-upload
              v-model:file-list="fileList"
              name="file"
              :multiple="true"
              action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              :customRequest="customRequestFile"
              :showUploadList="false"
            >
              <a-button type="primary">
                <upload-outlined />
                上传文件
              </a-button>
            </a-upload>
            <a-button type="link" v-if="fileName" @click="downloadFile">报名附件.zip</a-button>
            <div v-if="percent > 0">
              <a-progress :percent="percent">
                <template #format="percent">
                  <span>{{ percent }}%({{ percent == 100 ? '上传成功' : '上传中...' }})</span>
                </template>
              </a-progress>
            </div>
          </a-form-item>
          <a-form-item label="其他" name="remark">
            <a-textarea v-model:value="applicationForm.remark" :rows="4" />
          </a-form-item>
          <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
            <!-- <a-button type="primary" @click="onSubmit">Create</a-button> -->
            <!-- <a-button style="margin-left: 10px" @click="resetForm">重置</a-button> -->
          </a-form-item>
        </div>
      </a-form>
    </div>

    <div class="steps-action">
      <a-button v-if="current < steps.length - 1" type="primary" @click="next">下一步</a-button>
      <a-button v-if="current == steps.length - 1" type="primary" @click="onSubmit"> 提交报名 </a-button>
      <a-button v-if="current > 0" style="margin-left: 8px" @click="prev">上一步</a-button>
    </div>
  </div>
</template>
<script setup>
// import { Dayjs } from 'dayjs';

  import { computed, watch, onUnmounted,createVNode } from 'vue';
  import { onMounted, reactive, ref, toRaw } from 'vue';
  import { loginApi } from '/@/api/system/login-api';
  import { useUserStore } from '/@/store/modules/system/user.js';
  // import type { UnwrapRef } from 'vue';
  import { message } from 'ant-design-vue';
  import { fileApi } from '/@/api/support/file-api';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { FILE_FOLDER_TYPE_ENUM } from '/@/constants/support/file-const';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { useTeachertionStore } from '/@/store/modules/system/teachertion';
  import { registrationReviewApi } from '/@/api/registrationReview/index';
  import { useRouter } from 'vue-router';
import { after } from 'lodash';


  const baseUrl = import.meta.env.VITE_APP_API_URL;
  const current = ref(0);

  const next = () => {
    if (current.value !== 2) {
      formRef.value.validate().then(() => {
        current.value++;
        if (current.value == 0) {
          rules.value = rules1;
        } else if (current.value == 1) {
          rules.value = rules2;
        } else if (current.value == 4) {
          rules.value = rules3;
        } else if (current.value == 5) {
          rules.value = rules4;
        }
      });
    } else {
      current.value++;
    }
  };
  const prev = () => {
    current.value--;
    if (current.value == 0) {
      rules.value = rules1;
    } else if (current.value == 1 || current.value == 3) {
      rules.value = rules2;
    } else if (current.value == 4) {
      rules.value = rules3;
    } else if (current.value == 5) {
      rules.value = rules4;
    }
  };
  // formlist
  const formList = ref([
    { label: '身高', name: 'height', type: 'inputNumber' },
    { label: '固定电话', name: 'fixedTelephone', type: 'input' },
    {
      label: '户籍性质',
      name: 'houseType',
      type: 'radio',
      options: [
        { label: '农', value: 0 },
        { label: '非农', value: 1 },
      ],
    },
    { label: '生源地', name: 'sourceOrigin', type: 'input' },
    { label: '职称', name: 'title', type: 'input' },
    { label: '职称评定时间', name: 'titleDate', type: 'datePicker' },
    {
      label: '是否师范生',
      name: 'normalStudent',
      type: 'radio',
      options: [
        { label: '否', value: 0 },
        { label: '是', value: 1 },
      ],
    },
    // { label: '学历', name: '', type: 'input' },
    // { label: '学位', name: 'academicDegree', type: 'input' },
    {
      label: '是否应届生',
      name: 'freshGraduates',
      type: 'radio',
      options: [
        { label: '否', value: 0 },
        { label: '是', value: 1 },
      ],
    },
    // { label: '普通话发证地', name: 'mandarinPlace', type: 'input' },
    // { label: '计算机等级', name: 'computerLevel', type: 'input' },
  ]);
  const dataSource1 = ref([]);
  const dataSource2 = ref([]);
  const columns1 = ref([
    {
      title: '入学时间',
      dataIndex: 'enrollmentDate',
      key: 'enrollmentDate',
    },
    {
      title: '毕业时间',
      dataIndex: 'graduationDate',
      key: 'graduationDate',
    },
    {
      title: '所在学校',
      dataIndex: 'school',
      key: 'school',
    },
    {
      title: '职务',
      dataIndex: 'post',
      key: 'post',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      slots: { customRender: 'operation' },
    },
  ]);
  const columns2 = ref([
    {
      title: '颁发时间',
      dataIndex: 'issuanceDate',
      key: 'issuanceDate',
    },
    {
      title: '颁发部门',
      dataIndex: 'issuanceDepartment',
      key: 'issuanceDepartment',
    },
    {
      title: '奖项名称',
      dataIndex: 'awardName',
      key: 'awardName',
    },
    {
      title: '等级',
      dataIndex: 'grade',
      key: 'grade',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      slots: { customRender: 'operation' },
    },
  ]);
  //岗位代码
  const jobCodeList = ref([
    { label: '教师', value: '教师' },
    { label: '保健教师', value: '保健教师' },
  ]);
  // 政治面貌
  const politicalList = [
    {
      title: '中共党员',
      content: '中共党员',
    },
    {
      title: '中共预备党员',
      content: '中共预备党员',
    },
    {
      title: '共青团员',
      content: '共青团员',
    },
    {
      title: '群众',
      content: '群众',
    },
    {
      title: '其他政治面貌',
      content: '其他政治面貌',
    },
  ];
  // 婚姻状况
  const maritalList = [
    {
      title: '未婚',
      content: '未婚',
    },
    {
      title: '已婚',
      content: '已婚',
    },
    {
      title: '离异',
      content: '离异',
    },
    {
      title: '丧偶',
      content: '丧偶',
    },
  ];
  // 英语等级
  const englishList = [
    {
      title: '无',
      content: '无',
    },
    {
      title: '大学四级',
      content: '大学四级',
    },
    {
      title: '大学六级',
      content: '大学六级',
    },
    {
      title: '专业四级',
      content: '专业四级',
    },
    {
      title: '专业八级',
      content: '专业八级',
    },
  ];
  // 普通话等级
  const mandarinList = [
    {
      title: '无',
      content: '无',
    },
    {
      title: '一级甲等',
      content: '一级甲等',
    },
    {
      title: '一级乙等',
      content: '一级乙等',
    },
    {
      title: '二级甲等',
      content: '二级甲等',
    },
    {
      title: '二级乙等',
      content: '二级乙等',
    },
    {
      title: '三级甲等',
      content: '三级甲等',
    },
    {
      title: '三级乙等',
      content: '三级乙等',
    },
  ];
  // 教师资格证类别
  const teacherCardTypeList = [
    {
      title: '无',
      content: '无',
    },
    {
      title: '幼儿园教师资格',
      content: '幼儿园教师资格',
    },
    {
      title: '小学教师资格',
      content: '小学教师资格',
    },
    {
      title: '初级中学教师资格 ',
      content: '初级中学教师资格',
    },
    {
      title: '高级中学教师资格',
      content: '高级中学教师资格',
    },
    {
      title: '中等职业学校教师资格',
      content: '中等职业学校教师资格',
    },
    {
      title: '中等职业学校实习指导教师资格',
      content: '中等职业学校实习指导教师资格',
    },
    {
      title: '高等学校教师资格',
      content: '高等学校教师资格',
    },
  ];
  // 教师资格证学科
  const SubjectList = ref(['无']);
  const SubjectList0 = ref(['幼儿教育学科', '学前教育', '其他']);
  // 小学
  const SubjectList1 = ref([
    '‌语文‌',
    '‌数学‌',
    '‌英语‌',
    '‌社会‌',
    '‌科学‌',
    '‌体育‌',
    '‌音乐‌',
    '‌美术‌',
    '‌信息技术‌',
    '‌小学全科‌',
    '‌心理健康教育',
    '其他',
  ]);
  const SubjectList2 = ref([
    '‌语文‌',
    '‌数学‌',
    '‌英语‌',
    '‌思想品德‌',
    '‌历史‌',
    '‌地理‌',
    '‌物理‌',
    '‌化学‌',
    '‌生物‌',
    '‌音乐‌',
    '‌体育与健康‌',
    '‌美术‌',
    '‌信息技术‌',
    '‌历史与社会‌',
    '‌科学‌',
    '‌日语‌',
    '‌俄语‌',
    '‌心理健康教育',
    '其他',
  ]);
  const SubjectList3 = ref([
    '语文‌',
    '‌数学‌',
    '‌英语‌',
    '‌思想政治‌',
    '‌历史‌',
    '‌地理‌',
    '‌物理‌',
    '‌化学‌',
    '‌生物‌',
    '‌音乐‌',
    '‌体育与健康‌',
    '‌美术‌',
    '‌信息技术‌',
    '‌通用技术‌',
    '‌日语‌',
    '‌俄语‌',
    '‌心理健康教育',
    '其他',
  ]);
  function teacherCardTypeChange(value) {
    SubjectList.value = [];
    if (value === '小学教师资格') {
      SubjectList.value = SubjectList1.value;
    } else if (value === '无') {
      SubjectList.value = ['无'];
    } else if (value === '初级中学教师资格') {
      SubjectList.value = SubjectList2.value;
    } else if (value === '幼儿园教师资格') {
      SubjectList.value = SubjectList0.value;
    } else {
      SubjectList.value = SubjectList3.value;
    }
  }
  //学位
  const academicDegreeList = [
    {
      title: '学士',
      content: '学士',
    },
    {
      title: '硕士',
      content: '硕士',
    },
    {
      title: '博士',
      content: '博士',
    },
  ];
  // 学历
  const educationList = [
    {
      title: '本科',
      content: '本科',
    },
    {
      title: '硕士研究生',
      content: '硕士研究生',
    },
    {
      title: '博士研究生',
      content: '博士研究生',
    },
  ];
  // 表单填写步骤组件
  const steps = [
    {
      title: '报名学校',
      content: '0',
    },
    {
      title: '个人信息',
      content: '1',
    },
    {
      title: '本人简历',
      content: '2',
    },
    {
      title: '证书及获奖情况',
      content: '3',
    },
    {
      title: '资格信息',
      content: '4',
    },
    {
      title: '毕业信息',
      content: '5',
    },
  ];

  const hireTypeList = ref([
    {
      label: '教育系统',
      value: '教育系统',
    },
    {
      label: '社区学院',
      value: '社区学院',
    },
  ]);
  const items = steps.map((item) => ({ key: item.title, title: item.title }));
  const formRef = ref();
  const labelCol = { span: 8 };
  const wrapperCol = { span: 10 };
  const applicationForm = reactive({
    registerNum: '', //报名序号
    registerType: '', //报名学校类别
    registerSchool: '', //报名任教学校
    jobCode: '', //岗位代码
    hireType: '',
    actualName: '', //姓名
    employeeId: '',
    loginName: '', //登录名
    gender: '', //性别
    birthday: undefined, //出生年月
    card: '', //身份证号
    mailAddress: '', //通讯地址
    postalCode: '', //邮政编码
    phone: '', //手机号码
    houseLocation: '', //户籍所在地
    ethnicGroupId: '', //名族
    political: '', //政治面貌
    marital: '', //婚姻状况
    createtime: '', //名族
    english: '', //英语等级
    mandarin: '', //普通话等级
    teacherCardType: '', //教师资格证类别
    teacherCardSubject: '', //教师资格证学科
    education: '', //学历
    almaMater: '', //就读院校
    graduationData: '', //毕业时间
    enrollmentData: '', //入校时间
    major: '', //主修专业
    email: '', //邮箱
    registerScool: '',
    picUrl: '',
    height: '', //身高
    houseType: '', //户籍性质
    sourceOrigin: '', //生源地
    title: '', //职称
    titleDate: '', //职称评定时间
    fixedTelephone: '', //固定电话
    academicDegree: '', //学位
    normalStudent: '', //是否师范生
    freshGraduates: '', //是否应届生
    mandarinPlace: '', //普通话发证地
    computerLevel: '', //计算机等级
    resumeEntities: [], //本人简历
    certificateEntities: [], //证书或奖项
    fileUrl: '', //文件
    remark: '',
  });
  const props = defineProps({
    value: String,
    buttonText: {
      type: String,
      default: '点击上传附件',
    },
    showUploadBtn: {
      type: Boolean,
      default: true,
    },
    defaultFileList: {
      type: Array,
      default: () => [],
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    // 最多上传文件数量
    maxUploadSize: {
      type: Number,
      default: 10,
    },
    maxSize: {
      type: Number,
      default: 10,
    },
    // 上传的文件类型
    accept: {
      type: String,
      default: '',
    },
    // 文件上传类型
    folder: {
      type: Number,
      default: FILE_FOLDER_TYPE_ENUM.COMMON.value,
    },
    // 上传列表的内建样式，支持三种基本样式 text, picture 和 picture-card
    listType: {
      type: String,
      default: 'picture-card',
    },
  });

  // 图片类型的后缀名
  const imgFileType = ['jpg', 'jpeg', 'png', 'gif'];

  // 重新修改图片展示字段
  const files = computed(() => {
    let res = [];
    if (props.defaultFileList && props.defaultFileList.length > 0) {
      props.defaultFileList.forEach((element) => {
        // element.url = element.fileUrl;
        // element.name = element.fileName;
        res.push(element);
      });
      return res;
    }
    return res;
  });
  const emit = defineEmits(['update:value', 'change']);

  const rules2 = {
    actualName: [{ required: true, message: '请填写姓名', trigger: 'change' }],
    picUrl: [{ required: true, message: '请上传照片', trigger: 'change' }],
    gender: [{ required: true, message: '请填写性别', trigger: 'change' }],
    birthday: [{ required: true, message: '请选择出生年月', trigger: 'change' }],
    card: [{ required: true, message: '请填写身省证件号', trigger: 'change' }],
    mailAddress: [{ required: true, message: '请填写通讯地址', trigger: 'change' }],
    postalCode: [{ required: true, message: '请填写邮政编码', trigger: 'change' }],
    phone: [{ required: true, message: '请填写手机号码', trigger: 'change' }],
    houseLocation: [{ required: true, message: '请填写户籍所在地', trigger: 'change' }],
    ethnicGroupId: [{ required: true, message: '请填写民族', trigger: 'change' }],
    political: [{ required: true, message: '请填写政治面貌', trigger: 'change' }],
    marital: [{ required: true, message: '请填写婚姻状况', trigger: 'change' }],
    height: [{ required: true, message: '请填写身高', trigger: 'change' }], //身高
    houseType: [{ required: true, message: '请填写户籍性质', trigger: 'change' }], //户籍性质
    sourceOrigin: [{ required: true, message: '请填写生源地', trigger: 'change' }], //生源地
    normalStudent: [{ required: true, message: '请选择是否师范生', trigger: 'change' }], //是否师范生
    freshGraduates: [{ required: true, message: '请选择是否应届生', trigger: 'change' }], //是否应届生
  };

  const rules1 = {
    registerNum: [{ required: true, message: '请填写报名序号', trigger: 'change' }],
    registerType: [{ required: true, message: '请选择报名学校类别', trigger: 'change' }],
    registerSchool: [{ required: true, message: '请选择报名任教学校', trigger: 'change' }],
    jobCode: [{ required: true, message: '请选择岗位代码', trigger: 'change' }],
    subject: [{ required: true, message: '请选择学科', trigger: 'change' }],
    hireType: [{ required: true, message: '请选择报名类别', trigger: 'change' }],
  };
  const rules3 = {
    english: [{ required: true, message: '请选择英语等级', trigger: 'change' }],
    mandarin: [{ required: true, message: '请选择普通话等级', trigger: 'change' }],
    // mandarinPlace: [{ required: true, message: '请填写普通话发证地', trigger: 'change' }], //普通话发证地
    computerLevel: [{ required: true, message: '请填写计算机等级', trigger: 'change' }], //计算机等级
    teacherCardType: [{ required: true, message: '请选择教师资格证类别', trigger: 'change' }],
  };
  const rules4 = {
    almaMater: [{ required: true, message: '请选择就读院校', trigger: 'change' }],
    enrollmentData: [{ required: true, message: '请填写入校时间', trigger: 'change' }],
    education: [{ required: true, message: '请选择学历', trigger: 'change' }],
    academicDegree: [{ required: true, message: '请选择学历', trigger: 'change' }],
    major: [{ required: true, message: '请填写主修专业', trigger: 'change' }],
    fileUrl: [{ required: true, message: '请上传附件', trigger: ['change', 'blur'] }],
  };
  const rules = ref(rules1);
  function stepsChange(current) {
    if (current.value == 0) {
      rules.value = rules1;
    } else if (current.value == 1) {
      rules.value = rules2;
    } else if (current.value == 4) {
      rules.value = rules3;
    } else if (current.value == 5) {
      rules.value = rules4;
    }
  }
  const ethnicGroupList = ref([]);
  const registerTypeList = ref([]);
  const registerSchoolList = ref([]);

  const subjectList22 = ref([]); //报名学科
  let oldSchool = '';
  // 信息回显
  const detailType = ref(false);
  async function getDetail() {
    try {
      let result = await registrationReviewApi.selectById({ employeeId: useUserStore().employeeId });
      let data = result.data;
      oldSchool = data.registerSchool;
      if (data) {
        detailType.value = true;
        fileName.value = '附件';
        Object.assign(applicationForm, data);
        if (data.resumeEntities && data.resumeEntities.length) {
          dataSource1.value = data.resumeEntities;
        }
        if (data.certificateEntities && data.certificateEntities.length) {
          dataSource2.value = data.certificateEntities;
        }
        if( applicationForm.picUrl !== '' && applicationForm.picUrl !== null){
         
          fileList.value.push({
            url: baseUrl + '/upload/' + applicationForm.picUrl,
          });
        }
      }

      // Object.assign(form, data);
      // nextTick(() => {
      //     // 省市区不存在，不需要赋值
      //     if (!data.provinceName) {
      //         return;
      //     }
      //     area.value = [
      //         {
      //             value: data.province,
      //             label: data.provinceName,
      //         },
      //         {
      //             value: data.city,
      //             label: data.cityName,
      //         },
      //         {
      //             value: data.district,
      //             label: data.districtName,
      //         },
      //     ];
      // });
    } catch (error) {
      smartSentry.captureError(error);
    } finally {
      SmartLoading.hide();
    }
  }

  const router = useRouter();
  const onSubmit = () => {
    Modal.confirm({
      title: '确认信息',
      icon: createVNode(ExclamationCircleOutlined),
      content: '本人承诺：填报提交的信息和材料均真实有效，如有不实或不符合招聘条件, 由此造成的一切后果，责任自负。若被聘用，单位可随时解除聘用关系。',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        formRef.value
          .validate()
          .then(async () => {
            if (dataSource1.value && dataSource1.value.length > 1) {
              applicationForm.resumeEntities = dataSource1.value.filter((item) => {
                if (item.enrollmentDate && item.graduationDate && item.school && item.post) {
                  return item;
                }
              });
            } else {
              message.error('请最少填写两条个人简历！');
              return;
            }
            if (dataSource2.value && dataSource2.value.length) {
              applicationForm.certificateEntities = dataSource2.value.filter((item) => {
                if (item.issuanceDate && item.issuanceDepartment && item.awardName && item.grade) {
                  return item;
                }
              });
            }
            // if (!fileList.value.length) {
            //   message.error('请上传照片！')
            //   return
            // }
            // console.log('values', applicationForm, toRaw(applicationForm));
            const res = await loginApi.applicationSave(applicationForm);
            // console.log(res);
            if (res.code == 0) {
              message.success(res.msg);
              router.push('/home');
            } else {
              message.error(res.msg);
            }
          })
          .catch((error) => {
            console.log('error', error);
          });
      },
    });
    return;
  };
  /*function beforeUpload(file, files) {
  const suffixIndex = file.name.lastIndexOf('.');
  const fileSuffix = file.name.substring(suffixIndex <= -1 ? 0 : suffixIndex);
  if (accept.value.indexOf(fileSuffix) === -1) {
    // message.error(`只支持上传 ${accept.value.replaceAll(',', ' ')} 格式的文件`);
    return false;
  }

  const isLimitSize = file.size / 1024 / 1024 < maxSize.value;
  if (!isLimitSize) {
    message.error(`单个文件大小必须小于 ${maxSize.value} Mb`);
    return false;
  }
  return true;
}*/
  // const pushAdd = () => {
  //   message.success('Processing complete!');
  //   console.log(applicationForm);
  // };
  const resetForm = () => {
    formRef.value.resetFields();
  };

  // 图片上传
  function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });
  }
  const previewVisible = ref(false);
  const previewImage = ref('');
  const previewTitle = ref('');
  /*const fileList = ref([
  {
    uid: '-1',
    name: 'image.png',
    status: 'done',
    url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  },
]);*/
  const fileList = ref([]);
  // 头像地址
  // let picUrl = ref();
  const percent = ref(0);
  const fileName = ref('');
  function uploadProgressCallback(progressEvent) {
    // 计算进度，progressEvent.loaded是已上传的字节数，progressEvent.total是需要上传的总字节数
    const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
    percent.value = progress;
  }
  const customRequestFile = (options) => {
    const formData = new FormData();
    formData.append('file', options.file);
    formData.append('folder', 2);
    fileApi.uploadZip(formData, uploadProgressCallback).then((res) => {
      if (res.code === 0) {
        applicationForm.fileUrl = res.data.fileKey;
        fileName.value = res.data.fileName;
      }
    });
  };
  watch(
    files,
    (value) => {
      fileList.value = value;
    },
    {
      immediate: true,
    }
  );

  // 判断图片类型
  function isImg(fileType) {
    return imgFileType.includes(fileType);
  }
  function handleChange(info) {
    let fileStatus = info.file.status;
    let file = info.file;
    if (fileStatus === 'removed') {
      let index = fileList.value.findIndex((e) => e.fileId === file.fileId);
      if (index !== -1) {
        fileList.value.splice(index, 1);
        emit('change', fileList.value);
      }
      
    }
  }
  const handleCancel = () => {
    previewVisible.value = false;
    previewTitle.value = '';
  };
  const handlePreview = async (file) => {
    // console.log(file, file.fileKey);
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    // previewImage.value = file.url || file.preview;

    previewImage.value = file.preview || baseUrl + '/upload/' + file.fileKey;
    previewVisible.value = true;
    previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
  };

  async function customRequest(options) {
    // console.log(options);
    SmartLoading.show();
    try {
      if (!isImg(options.fileType)) {
        const formData = new FormData();
        formData.append('file', options.file);
        // console.log(options);
        let res = await fileApi.upPic(formData, props.folder);
        // console.log(res);
        let file = res.data;
        // picUrl.value = file;
        // console.log(picUrl)
        // file.url = file.picUrl;wwwwwwwwwwwwwwwwwwwww
        applicationForm.picUrl = file.fileKey;
        file.url = baseUrl + '/upload/' + file.fileKey;
        file.name = file.fileName;
        // fileList.value.push(file);
        fileList.value = [file];
        emit('change', fileList.value);
        options.onSuccess(res.data, res.code);
      }
      // SmartLoading.hide();
      // 更新头像
      // let updateAvatarForm = { avatar: file.fileKey };
      // await employeeApi.updateAvatar(updateAvatarForm);
      // message.success('更新成功');
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // 表格
  const onDelete1 = (record) => {
    dataSource1.value = dataSource1.value.filter((item) => item.sort !== record.sort);
  };
  const handleAdd1 = () => {
    if (dataSource1.value && dataSource1.value.length) {
      let flg = false;
      dataSource1.value.forEach((item) => {
        if (!item.enrollmentDate || !item.graduationDate || !item.school || !item.post) {
          flg = true;
        }
      });
      if (flg) {
        message.error('请填写完整后再添加！');
        return;
      }
    }
    const newData = {
      key: dataSource1.value.length ? dataSource1.value[dataSource1.value.length - 1].sort + 1 : 0,
      enrollmentDate: '',
      graduationDate: '',
      school: '',
      post: '',
      sort: dataSource1.value.length ? dataSource1.value[dataSource1.value.length - 1].sort + 1 : 0,
    };
    dataSource1.value.push(newData);
  };
  const onDelete2 = (key) => {
    dataSource2.value = dataSource2.value.filter((item) => item.sort !== key);
  };
  const handleAdd2 = () => {
    const newData = {
      key: dataSource2.value.length ? dataSource2.value[dataSource2.value.length - 1].sort + 1 : 0,
      issuanceDate: '',
      issuanceDepartment: '',
      awardName: '',
      grade: '',
      sort: dataSource2.value.length ? dataSource2.value[dataSource2.value.length - 1].sort + 1 : 0,
    };
    dataSource2.value.push(newData);
  };
  function downloadFile() {
    let link = document.createElement('a'); // 创建下载的实体标签
    link.href = baseUrl + '/upload/' + applicationForm.fileUrl; // 创建下载的链接
    link.download = '附件' + '.zip'; // 下载的文件名
    link.click(); // 执行下载
    link.remove();
  }
  // 学校数据
  const schooleData = ref([]);
  function schooleTypeChange(value) {
    registerSchoolList.value = schooleData.value
      .filter((item) => item.type === value)
      .map((i) => {
        return { label: i.name, value: i.name, subjects: i.subjects };
      });
    chengeSubjct();
    applicationForm.subject = '';
    applicationForm.registerSchool = '';
  }
  function registerSchoolChange(value) {
    chengeSubjct();
    if (applicationForm.isSignUp == 1) {
      // 如果目前选中的值不等于旧值就给它一个提示
      if (value !== oldSchool) {
        message.warning('检测到报名任教学校修改，请重新上传附件');
      }
    }
  }

  function chengeSubjct() {
    subjectList22.value = [];
    if (applicationForm.registerType && applicationForm.registerSchool) {
      for (let i = 0; i < schooleData.value.length; i++) {
        if (schooleData.value[i].type == applicationForm.registerType && schooleData.value[i].name == applicationForm.registerSchool) {
          subjectList22.value = schooleData.value[i].subjects;
        }
      }
    }
  }
  // function registerSchoolChange(value){
  //   registerSchoolList.value.forEach(item=>{
  //     if(item.value === value){
  //       jobCodeList.value = item.subjects.map(i=>{
  //         return {label:i.subject,value:i.subject}
  //       })
  //     }
  //   })
  //   applicationForm.jobCode = ''
  // }
  onMounted(async () => {
    const { phone, card, email, gender, actualName, registerNum, loginName, employeeId } = useUserStore().getUserList;
    applicationForm.phone = phone;
    applicationForm.card = card;
    applicationForm.email = email;
    applicationForm.gender = gender;
    applicationForm.actualName = actualName;
    applicationForm.registerNum = registerNum;
    // applicationForm.hireType = hireType;
    applicationForm.loginName = loginName;
    applicationForm.employeeId = employeeId;

    if (card.length === 18) {
      // 对于18位身份证号码
      const year = card.slice(6, 10);
      const month = card.slice(10, 12);
      const day = card.slice(12, 14);
      const genderDigit = parseInt(card[16], 10);
      applicationForm.gender = genderDigit % 2 === 0 ? '2' : '1';
      applicationForm.birthday = `${year}-${month}-${day}`;
    }
    console.log(useTeachertionStore().$state.form);
    // else {
    //   return null; // 无效的身份证号码长度
    // }
    Object.assign(applicationForm, useTeachertionStore().$state.form);
    getDetail();
    const res = await loginApi.ethnicGroupSelect();
    ethnicGroupList.value = res.data.data;

    // const registerType = await loginApi.schoolType();
    // console.log(registerType)
    // registerTypeList.value = registerType.data.rows.map(i => {
    //   return { label: i.MC, value: i.ID }
    // });
    // console.log(registerTypeList.value)

    // 获取报名任教学校
    const schooleList = await loginApi.schoolList();
    schooleData.value = schooleList.data;
    // console.log(schooleList);
    let typelist = [];
    typelist = schooleList.data.map((i) => {
      return i.type;
    });
    // console.log([...new Set(typelist)]);
    registerTypeList.value = [...new Set(typelist)].map((item) => {
      return { label: item, value: item };
    });
    if (applicationForm.registerType) {
      registerSchoolList.value = schooleData.value
        .filter((item) => item.type === applicationForm.registerType)
        .map((i) => {
          return { label: i.name, value: i.name, subjects: i.subjects };
        });
    }

    chengeSubjct();
  });
  onUnmounted(() => {
    useTeachertionStore().setForm(applicationForm);
  });
</script>

<style scoped>
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }

  .steps-content {
    margin-top: 16px;
    border: 1px dashed #e9e9e9;
    border-radius: 6px;
    background-color: #fafafa;
    min-height: 400px;
    text-align: center;
    padding-top: 80px;
  }

  .steps-action {
    margin-top: 24px;
  }

  [data-theme='dark'] .steps-content {
    background-color: #2f2f2f;
    border: 1px dashed #404040;
  }
</style>
